﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using taigu.WeChat;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;


namespace taigu
{
    /*
    * 文件名:PostCommentsService
    * 功能：发帖评论管理实现类
    * 创建时间：2021-11-15
    * 作者:gavin
    */
    [Authorize]
    public class PostCommentsService : ApplicationService, IPostCommentsService
    {

        private readonly IRepository<WeChat.PostComments, Guid> _repository;
        private readonly IRepository<WeChat.WeChatUsers, Guid> _WeChatUsersrepository;
        public PostCommentsService(IRepository<WeChat.PostComments, Guid> repository, IConfiguration configuration, IRepository<WeChat.WeChatUsers, Guid> _WeChatUsers_repository)
        {
            this._configuration = configuration;
            this._repository = repository;
            this._WeChatUsersrepository = _WeChatUsers_repository;
        }
        private IConfiguration _configuration;

        [AllowAnonymous]
        [Route("/community/getCommentList"),HttpPost]
        public async Task<ResData<object>> GetListAsync(SearchPostCommentsDto searchPostInfoDto)
        {
            try
            {
                //创建一个查询集合上架的帖子
                var query = (from Comment in _repository
                            join user in _WeChatUsersrepository
                            on Comment.user_id equals user.Id
                             where user.Id.Equals(Comment.user_id) && Comment.status.Equals(PostStatus.启用)
                             && Comment.post_id.Equals(searchPostInfoDto.post_id)&&user.status==UserStatus.enabled
                             select new PostCommentsShowDto
                            {
                                nickName = user.nick_name,
                                 realName = user.real_name,
                                 avatarUrl = user.avatar_url,
                                comment_id = Comment.comment_id.ToString(),
                                content = Comment.content,
                                CreationTime = Comment.CreationTime

                            }).OrderByDescending(x=>x.CreationTime).ToList();
                //总条数
                int totalCount =query.Count();
                //当前页
                int pageIndex = (searchPostInfoDto.page - 1) * searchPostInfoDto.pageSize;
                query =query.Skip(pageIndex).Take(searchPostInfoDto.pageSize).ToList();
                var data = new {total=totalCount,list= query };
                return new  ResData<object>
                {
                    Status = ResStatus.成功,
                    Msg = "sucess",
                    Info = data
                };
            }
            catch (Exception ex)
            {
                return new ResData<object>
                {
                    Status = ResStatus.查询失败,
                    Msg = "sucess"+ex.Message,
                };
            }
        }
        
        /// <summary>
        /// 发帖
        /// </summary>
        /// <param name="createPostInfoDto">创建DTO</param>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("/community/createComment"),HttpPost]
        public async Task<ResData<string>> CreateAsync(PostCommentsCreateDto createPostInfoDto)
        {
            try
            {
                //当前用户如果不存在或是禁用，不可以操作 2021-11-27，后面改成aop
                var user = await _WeChatUsersrepository.GetAsync(x => x.Id == createPostInfoDto.user_id);
                if (user == null || user.status == UserStatus.disabled)
                {
                    return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
                }

                PostComments data = ObjectMapper.Map<PostCommentsCreateDto, PostComments>(createPostInfoDto);
                data.status = PostStatus.启用;
                data.CreationTime = System.DateTime.Now;
                var result = await _repository.InsertAsync(data);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
            catch
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
            }
          
        }
        [AllowAnonymous]
        [Route("/community/updateComment"), HttpPost]
        public async Task<ResData<string>> UpdateAsync(PostCommentsUpdateDto updatePostInfoDto)
        {
            PostComments postLike = await _repository.GetAsync(x => x.Id == updatePostInfoDto.id && x.post_id.ToString() == updatePostInfoDto.post_id);
            if (postLike == null)
            {
                PostComments data = ObjectMapper.Map<PostCommentsUpdateDto, PostComments>(updatePostInfoDto);
                data.status = PostStatus.启用;
                var result = await _repository.InsertAsync(data);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
            else
            {
                postLike.status = PostStatus.删除;
                await _repository.UpdateAsync(postLike);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
        }

        /// <summary>
        /// 删除帖子
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [AllowAnonymous]
        [Route("/community/deleteComment"), HttpPost]
        public async Task<ResData<string>> DeleteAsync(Guid id)
        {
            try
            {
                await _repository.DeleteAsync(id);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
            catch
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = "sucess", Info = "" };
            }

        }
    }
}
